package org.an.proj.contacts.ui.test;

import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import jp.wasabeef.picasso.transformations.BlurTransformation;
import jp.wasabeef.picasso.transformations.GrayscaleTransformation;
import jp.wasabeef.picasso.transformations.RoundedCornersTransformation;
import org.an.ku.util.DensityUtil;
import org.an.ku.util.StringUtil;
import org.an.proj.contacts.R;
import org.an.proj.contacts.net.service.retrofit.upload.ProgressPicassoDownloader;
import org.an.proj.contacts.ui.base.BaseActivity;

/**
 * Picasso centerCrop按给定尺寸裁剪图片，centerInside按尺寸等比缩放，两者都必须结合resize()或者fit()
 */
public class PicassoActivity extends BaseActivity {

  private ImageView mImageView;
  private String url =
    "http://image3.lianjia.com//x-xf//hdic-resblock//1d28bb3e-9575-4f87-82dc-8789b9288f6c.jpg.300x300.jpg";

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_picasso);
    mImageView = (ImageView) findViewById(R.id.imageView);
    loadCenter(url);
  }

  private void loadCenter(String url) {
    Picasso.with(this).load(url).fit().centerInside().into(mImageView);
  }

  /**
   * @param imgUrl 图片url
   * @param defaultRes 默认图
   * @param radius 圆角半径dp
   */
  private void loadRound(@Nullable String imgUrl, @DrawableRes int defaultRes, ImageView imageView,
    int radius) {
    // 如果想对默认图也设置圆角的话，就必须load 本地资源；
    // 如果需要centerCrop必须调用Picasso的centerCrop方法
    if (StringUtil.isEmpty(imgUrl)) {
      Picasso.with(this)
        .load(defaultRes)
        .transform(new RoundedCornersTransformation(DensityUtil.dip2px(this, radius), 0))
        .fit()
        .centerCrop()
        .into(imageView);
    } else {
      Picasso.with(this)
        .load(imgUrl)
        .error(defaultRes)
        .placeholder(defaultRes)
        .transform(new RoundedCornersTransformation(DensityUtil.dip2px(this, radius), 0))
        .fit()
        .centerCrop()
        .into(imageView);
    }
  }

  public void onClear(View view) {
    File cacheDir = ProgressPicassoDownloader.createDefaultCacheDir(this);
    for (File file : cacheDir.listFiles()) if (file.exists()) file.delete();
  }

  public void onBlue(View view) {
    // 模糊加灰
    Picasso.with(this)
      .load(R.drawable.bg_splash)
      .fit()
      .centerInside()
      .transform(new GrayscaleTransformation())
      .transform(new BlurTransformation(this, 10))
      .into(mImageView);
  }
}
